<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use Illuminate\Support\Facades\Hash;
use Config;

use Illuminate\Support\Facades\URL;
use App\Services\Wechatshare;

class WechatController extends Controller
{
   public function getConfig($key){
	    $config=array('app_id' => 'wxb8f879f3ecc43dc5',
    'secret' => 'aab68259b13c6dffd031870ec623108e',
	'redirect_uri'=>env('APP_URL') . '/wechat/oauthCallbackAmi');
	return !empty($config[$key]) ? $config[$key]:"";
   }
   public function oauthAmi(Request $request){
	if($request->shop_id!=""){
		$tolink='http://armindiary.mashizai.com/adminApp/#/pages/members/add-members/add-members?admin_code='.$request->admin_code.'&admin_name='.$request->admin_name.'&shop_id='.$request->shop_id;
		session(['admin_create_user'=> $tolink]);
	}else{
		session(['admin_create_user'=> '']);
	}

   $authUrl = "https://emedia.sbedian.com/auth/wxHtmAuth?appid=".$this->getConfig('app_id')."&redirect_uri=".$this->getConfig('redirect_uri')."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	    return redirect($authUrl);

    }

    public function oauthCallbackAmi(Request $request){

		$code=$request->code;
        // 获取 OAuth 授权结果用户信息
        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->getConfig('app_id').'&secret='.$this->getConfig('secret').'&code='.$code.'&grant_type=authorization_code';
		$user=$this->httpRequest($url,'GET');
        $info = json_decode($user,true);
        $wuser = DB::table('member_users')->where('openid', $info['openid'])->orderBy('muLoginDefault', 'desc')->first();
		$params=array();
        if($wuser){
            $params['muId'] = $wuser->muId;
			$params['mcId'] = $wuser->mcId;
			$params['muCode'] = $wuser->muCode;
			$params['muMobile'] = $wuser->muMobile;
			$params['openid'] = $wuser->openid;
			$params['muNickName'] = $wuser->muNickName;
			$params['muRealName'] = $wuser->muRealName;
            if(!empty($wuser->muReferrerId)){
                $refuser = DB::table('member_users')->where('muCode', $wuser->muReferrerId)->first();
                if($refuser){
                     $params['muReferrerName'] = $refuser->muRealName;
                }else{
                    $params['muReferrerName'] = "";
                }
             
            }else{
                $params['muReferrerName'] = "";
            }

			$params['muHeadUrl'] = $wuser->muHeadUrl;
        }else{

            $params['muId'] = "";
			$params['mcId'] = "";
			$params['muCode'] = "";
			$params['muMobile'] = "";
            $params['muReferrerName']="";
			//获取用户信息
			$url2='https://api.weixin.qq.com/sns/userinfo?access_token='.$info['access_token'].'&openid='.$info['openid'].'&lang=zh_CN';

			$userinfo=$this->httpRequest($url2,'GET');
			$info2 = json_decode($userinfo,true);
			$params['openid'] = $info['openid'];
			$params['muNickName'] = $info2['nickname'];
			$params['muRealName'] = $info2['nickname'];
			$params['muHeadUrl'] = $info2['headimgurl'];
			if(session('admin_create_user')!=""){
				$create_user_link=session('admin_create_user').'&openid='.$info['openid'].'&muHeadUrl='.$params['muHeadUrl'];
				session(['admin_create_user'=>'']);
				return redirect($create_user_link);
			}
        }
        $host="http://armindiary.mashizai.com/userCenter";
        $host_vue =$host."/#/pages/index/index?".http_build_query($params);
        return redirect($host_vue);
    }
	public static function httpRequest($url,$type='POST',$data="",$header=array()){
		$oCurl = curl_init();
		//print_r($data);exit;
		curl_setopt($oCurl, CURLOPT_URL, $url);
		curl_setopt($oCurl, CURLOPT_HTTPHEADER,$header);// 设置请求头, 有时候需要,有时候不用,看请求网址是否有对应的要求
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
		// 不用 POST 方式请求, 意思就是通过 GET 请求
		if($type!='get'){
			curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, $type);
			curl_setopt($oCurl, CURLOPT_POSTFIELDS, $data);

		}else{
			curl_setopt($oCurl, CURLOPT_POST, false);
		}
		$sContent = curl_exec($oCurl);
		curl_close($oCurl);
		return $sContent;
	}
    // 发送短信
	public function sendSms(Request $request){
        if(!$request->phone || strlen($request->phone)!=11){
            return response()->json(['code' => '1010', 'msg' => '手机号不正确', 'data' => []]);
        }
        if(session('phone' . $request->phone.'_time')!="" && time()-session('phone' . $request->phone.'_time')<=60){
            return response()->json(['code' => '1010', 'msg' => '验证码已发送，请1分钟之后再重新发送。', 'data' => []]);
        }

		$code = mt_rand(100000, 999999);
		$content = "您的验证码是：{$code}。请不要把验证码泄露给其他人。";
		$rst = $this->send_sms_fun($request->phone, $content);

		if($rst['code'] == '0'){
			session(['phone' . $request->phone => $code]);
            session(['phone' . $request->phone.'_time' => time()]);
			return response()->json(['code' => '0', 'msg' => '发送成功', 'data' => []]);
		}else{
            return response()->json(['code' => '1010', 'msg' => $rst['msg'], 'data' => []]);
        }
	}
    /**
 * 发送短信
 */
    public function send_sms_fun($mobile, $content){
        //短信接口地址
        $target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

        $post_data = "account=cf_lctuangou&password=53133bc442e26e77ee8dd33d1c5087cd&mobile=".$mobile."&content=".rawurlencode($content);
        //用户名是登录用户中心->验证码短信->产品总览->APIID
        //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
        $gets =  $this->xml_to_array($this->httpRequest($target,'POST',$post_data));

        $rtn['code'] = $gets['SubmitResult']['code'] == 2 ? '0' : '1002';
        $rtn['msg'] = $gets['SubmitResult']['msg'];
        return $rtn;
    }
	/**
 * 将 xml数据转换为数组格式。 ihuyi 短信需要
 */
	public function xml_to_array($xml){
	$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
	if(preg_match_all($reg, $xml, $matches)){
		$count = count($matches[0]);
		for($i = 0; $i < $count; $i++){
		$subxml= $matches[2][$i];
		$key = $matches[1][$i];
			if(preg_match( $reg, $subxml )){
				$arr[$key] = $this->xml_to_array( $subxml );
			}else{
				$arr[$key] = $subxml;
			}
		}
	}
	return $arr;
}
    // 绑定用户
	public function bindUser(Request $request){
        if(!$request->phone || strlen($request->phone)!=11){
            return response()->json(['code' => '1010', 'msg' => '手机号不正确', 'data' => []]);
        }
        if(!$request->openid || $request->openid==''){
            return response()->json(['code' => '1010', 'msg' => '用户openid不存在', 'data' => []]);
        }
        if(!$request->check_code || strlen($request->check_code)!=6){
            return response()->json(['code' => '1010', 'msg' => '验证码不正确', 'data' => []]);
        }
		if($request->check_code != session('phone' . $request->phone)){
            return response()->json(['code' => '1012', 'msg' => '验证码错误', 'data' => []]);
        }
		session(['phone' . $request->phone=>'']);
        $wuser = DB::table('member_users')->where('muMobile', $request->phone)->first();
        if($wuser){
            $params=array();
        	$params['openid'] = $request->openid;
        	$params['muNickName'] = $request->muNickName;
        	$params['muHeadUrl'] = $request->muHeadUrl;
            DB::table('member_users')->where('muMobile', $request->phone)->update($params);
        }else{
            /*$params=array();
        	$params['mcId'] = 0;
        	$params['muCode'] = md5($request->phone.$request->openid.rand(10000,99999));
        	$params['muMobile'] = $request->phone;
            $params['openid'] = $request->openid;
            $params['muNickName'] = $request->muNickName;
            $params['alId'] =5;
            $params['muSex'] =0;
			$params['muRealName'] = $request->muNickName;
            $params['muHeadUrl'] = $request->muHeadUrl;
            $params['createUser'] ='website';
            $params['createTime'] = date("Y-m-d H:i:s");
            $params['muPassword'] = 'e10adc3949ba59abbe56e057f20f883e';

        	DB::table('member_users')->insert($params);
            $wuser = DB::table('member_users')->where('muMobile', $request->phone)->first();*/
            return response()->json(['code' => '1013', 'msg' => '绑定手机号失败，请联系店铺管理员录入您的身份信息。', 'data' => []]);
        }
        if(!empty($wuser->muReferrerId)){
            $refuser = DB::table('member_users')->where('muCode', $wuser->muReferrerId)->first();
            if($refuser){
                $wuser->muReferrerName = $refuser->muRealName;
            }else{
                $wuser->muReferrerName = "";
            }
            
        }else{
            $wuser->muReferrerName = "";
        }
		return response()->json(['code' => '0', 'msg' =>'绑定用户成功' , 'data' => $wuser]);
	}
    /**
     * 自定义分享js
     * @param Request $request
     * @return array
     */
    public function wxJs(Request $request){
        if(empty($request->url)){
            return ['code' => '1010', 'msg' => '请设置url', 'data' => []];
        }
    
        $app = new Wechatshare($this->getConfig('app_id'),$this->getConfig('secret'));
        $config = $app->getSignPackage($request->url);
		//print_r($config);exit;
        return ['code' => '0', 'msg' => '成功', 'data' => $config];
    }
}
